package com.lopo.springSecurity.login.UP;

import cn.hutool.jwt.JWTUtil;
import com.beust.jcommander.internal.Maps;
import com.lopo.springSecurity.bean.AdminUser;
import com.lopo.springSecurity.config.BaseAuthenticationProvider;
import com.lopo.springSecurity.config.LoginSuccessToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;


@Component
@Slf4j
@RequiredArgsConstructor
public class AdminPasswordAuthenticationProvider extends BaseAuthenticationProvider implements
    AuthenticationProvider {

//  private final AdminUserRepository adminUserRepository;

//    private final SecurityProperties securityProperties;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AdminUsernamePasswordToken token = (AdminUsernamePasswordToken) authentication;
        if (ObjectUtils.isEmpty(token.getUsername()) || ObjectUtils.isEmpty(token.getPassword())) {
            throw new BadCredentialsException("用户不存在");
        }
//    Optional<AdminUser> adminUser = adminUserRepository.findByPhone(token.getUsername());
        final AdminUser adminUser = new AdminUser();
        adminUser.setUsername("lopo");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(token.getPassword(),
            adminUser.getPassword());
        if (1==1) {
            Map<String, Object> jwtInfo = Maps.newHashMap();
            jwtInfo.put("id", adminUser.getPhone());
            jwtInfo.put("type", "admin");
            String jwtToken = JWTUtil.createToken(jwtInfo,"123456".getBytes(StandardCharsets.UTF_8));
            return new LoginSuccessToken(jwtToken, adminUser.getUsername());
        } else {
            throw new BadCredentialsException("登录错误");
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return AdminUsernamePasswordToken.class.isAssignableFrom(aClass);
    }
}
